package com.chilly.jdkNio.action.hello;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.Iterator;
import java.util.Set;

/**
 * 编写一个NIO入门案例，实现服务器端和客户端之间的数据简单通讯（非阻塞）
 * 目的：理解NIO非阻塞网络编程机制
 * Created by Chilly Cui on 2021/1/10.
 */
public class NIOServer {

    public static void main(String[] args) throws IOException {
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();

        Selector selector = Selector.open();

        serverSocketChannel.socket().bind(new InetSocketAddress(6666));
        serverSocketChannel.configureBlocking(false);

        //把serverSocketChannel 注册到selector
        serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);

        //等待客户端连接
        while (true) {
            if (selector.select(1000) == 0) { //无事件发生
                System.out.println("服务器等待了1秒，无连接");
                continue;
            }
            Set<SelectionKey> selectionKeys = selector.selectedKeys();
            Iterator<SelectionKey> iter = selectionKeys.iterator();
            while (iter.hasNext()) {
                SelectionKey key = iter.next();
                if (key.isAcceptable()) { //如果是 OP_ACCEPT ，说明有新的客户度连接
                    SocketChannel clientSocketChannel = serverSocketChannel.accept();//获取客户端连接
                    //SocketChannel client = (SocketChannel) key.channel();
                    System.out.println("客户端连接成功");

                    clientSocketChannel.configureBlocking(false);

                    //把 客户度连接 注册到selector, 读事件，关联一个buffer
                    clientSocketChannel.register(selector, SelectionKey.OP_READ, ByteBuffer.allocate(1024));
                } else if (key.isReadable()) {
                    SocketChannel client = (SocketChannel) key.channel();
                    ByteBuffer buffer = (ByteBuffer) key.attachment();

                    client.read(buffer);
                    System.out.println("from 客户端：" + new String(buffer.array()));
                    buffer.clear();
                }

                //手动从集合中移除当前的selectionKey， 防止重复操作
                iter.remove();
            }
        }

    }
}
